class ItemsController < ApplicationController
  def get_inventory
    
    if params[:jobsite]
	  if params[:hours]
       @items = Item.where(:jobsite_id => params[:jobsite], :updated_at => ((Time.now - params[:hours].to_i.hours)..Time.now) )
	  else
	   @items = Item.where(:jobsite_id => params[:jobsite])
	  end
    else
	  if params[:hours]
       @items = Item.where(:updated_at => ((Time.now - params[:hours].to_i.hours)..Time.now) )
	  else
	   @items = Item.all
	  end
    end
    
    if @items      
      rtn_json(@items)
    else
      rtn_json({'error' => 'Error. Could not retrieve inventory'})
    end
  end
  
  def show
    @item = Item.find(params[:item_id])
    if @item
      rtn_json({'id' => @item.id,'status' => '200', 'name' => @item.name, 'quantity' => @item.quantity})
    else
      rtn_json({'error' => 'Error. Could not find the item.'})
    end    
  end
  
  def update
    @item = Item.find(params[:item_id])
    
    if params.has_key?(:name)
      @item.update_attribute(:name, params[:name])
    end
    
    if params.has_key?(:barcode)
      @item.update_attribute(:barcode_id, params[:barcode])
    end
    
    if(params.has_key?(:quantity))
      @item.update_attribute(:quantity, params[:quantity])
    end
    
    if(params.has_key?(:user_id))
      @item.update_attribute(:user_id, params[:user_id])
    end
    
    if(params.has_key?(:jobsite_id))
      @item.update_attribute(:jobsite_id, params[:jobsite_id])
    end
    
    if(params.has_key?(:device_id))
      @item.update_attribute(:device_id, params[:device_id])
    end
    
    @item.save
    
    rtn_json({'status' => '200'})    
  end
  
  def create
    @item = Item.new(:name => params[:name], 
                         :quantity => params[:quantity], 
                         :user_id =>params[:user_id], 
                         :barcode_id => params[:barcode],
                         :jobsite_id => params[:jobsite],
                         :device_id => params[:device_id])
                         
    device = Device.find(params[:device_id])
    
    if device.active != 1
      rtn_json({'error' => 'Device not enabled for item entry.'})
    end
    
    employee = User.find(params[:user_id])
    jobsite = Jobsite.find(params[:jobsite])
    
    @item.employee_name = employee.username
    @item.jobsite_name = jobsite.name
                         
    if @item.save
      rtn_json({'status' => '200', 'id' => @item.id})
    else
      rtn_json({'error' => 'Could not create item'})
    end
  end
  
  def destroy
    Item.find(params[:item_id]).destroy
    rtn_json('status' => '200')
  end
  
	# reading a CSV file uploaded by the user
	def importCSV
	  # return err if file not found
	  if !params[:file]
      info_msg = "<h3 style=\"color:red;font-family:Arial, Helvetica, sans-serif\">No uploaded file found</h3><input type=\"button\" class=\"btn\" value=\"Retry\" onClick=\"document.location.href = 'http://localhost/gocuro/csvupload.html'\"/>"
      respond_to do |format|
          format.html { render text: info_msg, :callback => params[:callback] }
      end
      return
    end
    
    # return err if file is not in the right format
    if params[:file].content_type != "application/vnd.ms-excel"
      info_msg = "<h3 style=\"color:red;font-family:Arial, Helvetica, sans-serif\">Chosen file is not windows xml format </h3><input type=\"button\" class=\"btn\" value=\"Retry\" onClick=\"document.location.href = 'http://localhost/gocuro/csvupload.html'\"/>"
      respond_to do |format|
          format.html { render text: info_msg, :callback => params[:callback] }
       end
      return
    end
		
		counter = 0
		file_data = params[:file].tempfile
		file_data.each_line do |line|
			if counter != 0
				# assume columns Inventory #  ,Item Name , Quantity , User_ID , Barcode_ID, Device_ID, Jobsite_id
				item_attribute = line.gsub("\n",'').gsub("\r",'').split(',')
				@item = Item.create(
					:name => item_attribute[0],
					:quantity => item_attribute[1], 
					:user_id => item_attribute[2], 
					:barcode_id => item_attribute[3],
					:jobsite_id => item_attribute[4],
					:device_id => item_attribute[5]			
				)
				employee = User.find(item_attribute[2].to_i)
				jobsite = Jobsite.find(item_attribute[4].to_i)
				@item.employee_name = employee.username
				@item.jobsite_name = jobsite.name
				@item.save
			end # end if
			counter += 1
		end # end do
		
	 info_msg = "<h3 style=\"color:green;font-family:Arial, Helvetica, sans-serif\">CSV imported successfully</h3><input type=\"button\" class=\"btn\" value=\"Import another file\" onClick=\"document.location.href = 'http://localhost/gocuro/csvupload.html'\"/>"
   respond_to do |format|
       format.html { render text: info_msg, :callback => params[:callback] }
   end
   
   return
	end # end importCSV
	
	# expoting a CSV file to the user
	def exportCSV
		@items = Item.all
		csv_string = "Name,Quantity,Username,Barcode,Jobsite,Device Number,Date Entered,Date Updated\r\n"
		@items.each do |item|
		  @user = User.find(item.user_id)
		  @jobsite = Jobsite.find(item.jobsite_id)
		  @device = Device.find(item.device_id)
			csv_string += "#{item.name},#{item.quantity},#{@user.username},#{item.barcode_id},#{@jobsite.name},#{@device.phone_number},#{item.created_at},#{item.updated_at}\r\n"
		end
		filename = "data-gocuro-export-#{Time.now.to_date.to_s}.csv"    
		send_data(csv_string, :type => 'text/csv; charset=utf-8; header=present', :filename => filename, :callback => params[:callback])  
	end # end exportCSV
  
  def rtn_json(obj)
    respond_to do |format|
      format.html{render json: obj, :callback => params[:callback]}
      format.json{render json: obj, :callback => params[:callback]}
    end
  end

  def exportCSVgetURL
	  rtn_json({'url' => "http://gocuro2.herokuapp.com/csv/export"})	 
  end  
  
end
